package com.tgy.myplus.基础学习.Thread.Synchronized;

import lombok.SneakyThrows;

/**
 * @author 送你一块二向箔
 * @date 2021/11/08 15:38
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100,"一号钱包");
        Drawing drawing = new Drawing(account,50,20);
        new Thread(new Drawing(account,50,20),"甲号取钱").start();
        new Thread(new Drawing(account,60,20),"乙号取钱").start();
    }

}


//账户
class Account {
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行
class Drawing implements Runnable{
    Account account;//账户
    int drawingMoney;//取钱
    int nowMoney;//手里得钱

    //构造器
    public Drawing(Account account, int drawingMoney, int nowMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.nowMoney = nowMoney;
    }


    @SneakyThrows
    @Override
    /**
     * synchronized 默认锁的时this
     * 下面这种是不行的
     */
    public synchronized void run() {
        if (account.money-drawingMoney<0){
            System.out.println(Thread.currentThread().getName()+"余额不足");
            return;
        }
        //模拟延时，放大问题发生得可能性
        Thread.sleep(100);
        account.money -=drawingMoney;
        nowMoney += drawingMoney;
        System.out.println(account.name+"余额为："+account.money);
        System.out.println(Thread.currentThread().getName()+"手里有："+nowMoney);

    }

}
